import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/utils.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../../hj_utils/global.dart';

class MineShareQRView extends StatefulWidget {
  const MineShareQRView({super.key});

  @override
  State<MineShareQRView> createState() => _MineShareQRViewState();
}

class _MineShareQRViewState extends State<MineShareQRView> {
  final boundaryKey = GlobalKey();
  int totalInvite = 0;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final record = await MineService.getProxyBindRecord(1, 1);
      totalInvite = record?.total ?? 0;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        RepaintBoundary(
          key: boundaryKey,
          child: _codeView(),
        ),
        SizedBox(height: 20),
        InkWell(
          onTap: () => _saveImage(),
          child: Container(
            height: 44,
            width: 184,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(22), color: AppColors.actionRed),
            alignment: Alignment.center,
            child: Text(
              "保存图片",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w500,
                fontSize: 16,
              ),
            ),
          ),
        ),
        TextButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: globalStore.meInfo?.promoteURL ?? ""));
              showToast('复制成功');
            },
            child: Text(
              "复制链接",
              style: TextStyle(
                color: Color(0xFFFFFFFF),
                decoration: TextDecoration.underline, // 添加下划线
                decorationColor: Color(0xFFFFFFFF), // 下划线颜色
                decorationThickness: 1.0, // 下划线粗细
                decorationStyle: TextDecorationStyle.solid, // 下划线样式
              ),
            ))
      ],
    );
  }

  Widget _codeView() {
    return Container(
      height: 372,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Image.asset(
            "qr_code_bg.webp".mineImgPath,
            height: 372,
            fit: BoxFit.fill,
          ),
          Positioned(
            top: 25,
            child: Column(
              children: [
                Image.asset(
                  'walfare_logo.webp'.mineImgPath,
                  height: 72,
                ),
                6.sizeBoxH,
                Image.asset(
                  'dash_line.webp'.mineImgPath,
                  width: 240,
                  height: 20,
                ),
                16.sizeBoxH,
                RichText(
                  textAlign: TextAlign.left,
                  text: TextSpan(
                    style: TextStyle(fontSize: 16, color: Color(0xFF989898)), // 默认样式
                    children: [
                      TextSpan(text: '累计邀请'),
                      TextSpan(
                        text: ' $totalInvite人',
                        style: TextStyle(color: AppColors.actionRed),
                      ),
                    ],
                  ),
                ),
                16.sizeBoxH,
                QrImageView(
                  data: globalStore.meInfo?.promoteURL ?? "",
                  version: QrVersions.auto,
                  size: 140,
                  backgroundColor: Colors.white,
                ),
                16.sizeBoxH,
                RichText(
                  textAlign: TextAlign.left,
                  text: TextSpan(
                    style: TextStyle(fontSize: 12, color: Color(0x73FFFFFF)), // 默认样式
                    children: [
                      TextSpan(text: '我的邀请码'),
                      WidgetSpan(
                        alignment: PlaceholderAlignment.middle,
                        child: Text(
                          ' ${globalStore.meInfo?.promotionCode ?? ""}',
                          style: TextStyle(color: AppColors.actionRed, fontSize: 24, fontWeight: FontWeight.w600),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///保存图片
  void _saveImage() async {
    Future.delayed(Duration(milliseconds: 20), () async {
      RenderRepaintBoundary? boundary = boundaryKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
      var image = await boundary?.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image?.toByteData(format: ImageByteFormat.png);
      bool suc = await savePngDataToAblumn(byteData?.buffer.asUint8List());
      if (suc) {
        showToast("保存成功");
      }
    });
  }
}
